
//
//  RequestManager.m
//  魔兽大数据
//
//  Created by 王右 on 2017/10/14.
//  Copyright © 2017年 王右. All rights reserved.
//

#import "RequestManager.h"
#import "RequestManager+Extand.h"
#import "CCJSONParse.h"
#import "CCCache.h"
#import "AppDelegate.h"



typedef enum : NSUInteger {
    kErrorCodeTokenFail = 1,    //认证失败
    kErrorCodeFail,             //失败
    kErrorCodeAccess,           //权限
} kErrorCode;

static NSString *const kHostDomain = @"http://180.101.204.50:8888/pms/app/";//此处需要更换为后台的HOST
static NSString *const kHostDomainNew = @"http://boxfen.sf-epiaotong.com/box-fans/api/";//此处需要更换为后台的HOST

static NSInteger const kTimeoutInterval =  15.0;


@implementation RequestManager

//header
+ (AFHTTPSessionManager*)afmanager {
    static AFHTTPSessionManager* manager = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json",@"text/plain",@"text/json",@"application/javascript",@"application/x-javascript" ,@"text/javascript",@"text/x-javascript",@"text/x-json",nil];
        manager.requestSerializer.timeoutInterval = kTimeoutInterval;
        
    });
    return manager;
}






+ (void)getRequestWithModule:(NSString *)module param:(NSDictionary *)param model:(NSString *)model success:(void (^)(id))success failure:(void (^)(NSString *))failure{
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定!");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomain,module];
    id result = [[CCCache defaultManager] objectForKey:url];
    if (result != nil) {
        //如果有网络请求缓存
        success(result);
        return;
    }
    [[self afmanager] GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        id data = resultObject;
        id result;
        Class objClass = NSClassFromString(model);
        if ([data isKindOfClass:[NSArray class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithArray:data ingoreChange:NO];
            }
            
        }
        if ([data isKindOfClass:[NSDictionary class]]) {
            if ([model isEqualToString:@""]) {
                result = [objClass objectWithDictionary:data ingoreChange:NO];
            }
        }
        success(result);
        /*此处可以对数据进行限时缓存*/
//        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定!");
    }];
}

+ (void)postRequestWithModule:(NSString *)module param:(NSDictionary *)param model:(NSString *)model success:(void (^)(id))success failure:(void (^)(NSString *))failure{
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定!");
        return;
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomain,module];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    request.timeoutInterval= kTimeoutInterval;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置body
    [request setHTTPBody:[self dictionaryToJson:param]];
    
    [[[self afmanager] dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (failure) {
                failure(@"服务器出错或网络不稳定!");
                return ;
            }
        }
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        if (httpResponse.statusCode != 200) {
            if (failure) {
                failure(@"服务器出错或网络不稳定!");
                return ;
            }
        }
        
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        id result;
        
        //token失效
        if ([resultObject[@"status"] intValue] == 300 && ![module isEqualToString:@"v1/login"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [(AppDelegate *)[UIApplication sharedApplication].delegate logout];
                return ;
            });
        }

        Class objClass = NSClassFromString(model);
        if ([resultObject isKindOfClass:[NSArray class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithArray:resultObject ingoreChange:NO];
            }

        }
        if ([resultObject isKindOfClass:[NSDictionary class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithDictionary:resultObject ingoreChange:NO];
            }
        }
        if (success) {
            success(resultObject);
        }
        
    }] resume] ;
}

+ (NSData *)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return jsonData;
}


+ (void)postNewRequestWithModule:(NSString *)module param:(NSDictionary *)param model:(NSString *)model success:(void (^)(id))success failure:(void (^)(NSString *))failure{
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定!");
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomainNew,module];
    [[self afmanager] POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        id result;
        Class objClass = NSClassFromString(model);
        if ([resultObject isKindOfClass:[NSArray class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithArray:resultObject ingoreChange:NO];
            }
            
        }
        if ([resultObject isKindOfClass:[NSDictionary class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithDictionary:resultObject ingoreChange:NO];
            }
        }
        success(result?:resultObject);
        /*此处可以对数据进行限时缓存*/
        //        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(@"服务器出错或网络不稳定!");
        }
    }];
}

+ (void)postRequestGetPhoneCodeWithPhone:(NSString *)phone success:(void (^)(id))success failure:(void (^)(NSString *))failure{
    NSDictionary *dic = @{@"phone":phone};
    NSString *module = @"common/sendVerificationCode";
    [self postRequestWithModule:module param:dic model:nil success:success failure:failure];
}

+ (void)uploadImageWithImage:(UIImage *)image success:(void (^)(id))success failure:(void (^)(NSString *))failure{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomain,@"v1/upload"];
    float jpgQuantity = 1.0f;
    int jpgMaxSize = 10 * 1024;
    NSData *imageData = UIImageJPEGRepresentation(image,jpgQuantity);
    while (jpgQuantity>0.1f && [imageData length]>jpgMaxSize) {
        jpgQuantity -= 0.1f;
        imageData = UIImageJPEGRepresentation(image,jpgQuantity);
    }
    
    [[self afmanager] POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //  调整质量，头像设置上传容量上限30k
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:imageData name:@"files" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)task.response;
        if (httpResponse.statusCode != 200) {
            if (failure) {
                failure(@"服务器出错或网络不稳定!");
            }
        }
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(resultObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(@"服务器出错或网络不稳定!");
        }
    }];
}



@end
